package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.LitemallPosterMapper;
import org.linlinjava.litemall.db.domain.LitemallPoster;
import org.linlinjava.litemall.db.domain.LitemallPosterExample;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class LitemallPosterService {
    @Resource
    private LitemallPosterMapper posterMapper;

    public List<LitemallPoster> queryIndex() {
        LitemallPosterExample example = new LitemallPosterExample();
        example.or().andDeletedEqualTo(false).andEnabledEqualTo(true);
        return posterMapper.selectByExample(example);
    }

    public List<LitemallPoster> querySelective(String name, String content, Integer page, Integer limit, String sort, String order) {
        LitemallPosterExample example = new LitemallPosterExample();
        LitemallPosterExample.Criteria criteria = example.createCriteria();

        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (!StringUtils.isEmpty(content)) {
            criteria.andContentLike("%" + content + "%");
        }
        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, limit);
        return posterMapper.selectByExample(example);
    }

    public int updateById(LitemallPoster poster) {
        poster.setUpdateTime(LocalDateTime.now());
        return posterMapper.updateByPrimaryKeySelective(poster);
    }

    public void deleteById(Integer id) {
        posterMapper.logicalDeleteByPrimaryKey(id);
    }

    public void add(LitemallPoster poster) {
        poster.setAddTime(LocalDateTime.now());
        poster.setUpdateTime(LocalDateTime.now());
        posterMapper.insertSelective(poster);
    }

    public LitemallPoster findById(Integer id) {
        return posterMapper.selectByPrimaryKey(id);
    }
}
